package com.demo.springboot.client;

import com.demo.springboot.client.util.LoadBalance;
import com.demo.springboot.server.web.Response;
import com.google.gson.Gson;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryOneTime;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
import org.apache.curator.x.discovery.ServiceInstance;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/***
 * 服务的发现：
 *      在进行服务调用的时候，需要先从注册中心获取到服务的地址，然后根据获取到的服务地址进行调用
 */

public class Client {

    public static void main(String[] args) throws Exception {

        String zkAddress = "127.0.0.1:2181";
        CuratorFramework client = CuratorFrameworkFactory.newClient(zkAddress, new RetryOneTime(1000));
        client.start();
        client.blockUntilConnected();

        ServiceDiscovery<Object> discovery = ServiceDiscoveryBuilder.builder(Object.class).client(client).basePath(
            "/soa").build();

        Collection<ServiceInstance<Object>> serviceInstances = discovery.queryForInstances("product");

        List<String> servers = new ArrayList<>();
        serviceInstances.forEach((serviceInstance) -> {
            String address = serviceInstance.getAddress();
            Integer port = serviceInstance.getPort();
            servers.add("http://" + address + ":" + port);
        });

        LoadBalance balance = new LoadBalance(servers);
        for (int i = 0; i < 10; i++) {
            String hostUrl = balance.choose();
            RestTemplate rt = new RestTemplate();
            String body = rt.getForObject(hostUrl + "/soa/product/version", String.class);
            System.out.println(body);
            Response response = new Gson().fromJson(body, Response.class);
            System.out.println(response);
        }
    }
}
